const app = getApp();
const Controller = require('../controllers/controllers.js').controller;
const {
  Today,
  formatTime2,
  formatTime3,
  randomNum
} = require('../../utils/util.js');
const manage = wx.getBackgroundAudioManager()
const SEQUENCE_MODE = 1
const RANDOM_MOD = 2
const SINGLE_CYCLE_MOD = 3

Page({
  data: {
    title: '首页',
    banner: [],
    current: 0,
    mode: 1,
    play: 1,
    meau: [],
    albumnav: ["专题", "热播", "推荐", "达人"],
    albumnavcurrent: 0,
    ishot: true,
    singnav: [],
    singnavdata: [],
    singnavdataleft: [],
    singnavdataright: [],
    singnavcurrent: 0,
    singnavleft: 0,
    isprev: false,
    isnext: true,
    singnavleftend: false,
    navHeight: 66,
    defaulttopheight: 400,
    signbool: false,

    loadingbool: true,
    isFixedTop: false,
    adverstisedata: '',
    adverstise2data: '',
    adverstisetime: 3,
    signListdata: [],
    signmoth: '',
    issign: false,
    page: 1,
    pageSize: 10,
    isEnd: false,
    singnavid: '',
    singnavpage: 1,
    singnavpageSize: 10,
    singnavisEnd: false,
    compilationpage: 1,
    compilationpageSize: 10,
    compilationisEnd: false,
    isTopic: 1,
    isMust: 0,
    sortBy: 2,
    albumlists1: [],
    albumlists2: [],
    iscanSign: null,

    currentTime: 0,
    playurl: '',
    currentLyric: null,
    currentLineNum: 0,
    toLineNum: -1,
    currentSong: null,
    playMod: SEQUENCE_MODE,
    closetimecurrent: 0,
    settimebool: false,
    percent: 0,
    sildercurrent:0,
    currentmonth: '',
    actList: [{
      id: 1,
      title: '如果努力需要理由，我想这就是答案',
      activityBanner: 'https://youyang-cdn.mdshuzhi.com/upload/封面.jpg'
    }, {
      id: 2,
      title: '吵架后，“冷静一下”有用吗？',
      activityBanner: 'https://youyang-cdn.mdshuzhi.com/upload/封面2.jpg'
    }, {
      id: 3,
      title: '免疫功能失调时，应该怎么办？',
      activityBanner: 'https://youyang-cdn.mdshuzhi.com/upload/封面3.jpg'
    }], //活动列表

    isReady: false, //配置接口是否请求完毕 接接口时这里默认改为false 请求成功就改为true
    isShow: false, //是否显示正常页面
    singnisloading:true,
  },
  /**跳转文章详情 */
  toDetail(e) {
    let {
      id,
      title
    } = e.currentTarget.dataset
    wx.navigateTo({
      url: '../../pages/Article/Article?id=' + id + '&title=' + title,
    })
  },
  config() {
    Controller.info({
      key: 'key-allow-access'
    }).then(res => {
      this.setData({
        isReady: true
      })
      if (res.data.baseData && res.data.baseData.content == 1) {
        this.setData({
          isShow: false
        })
        wx.reLaunch({ url: '/page/index/index' });
      } else {
        this.setData({
          isShow: true
        })
        this.setData({
          navHeight: app.globalData.navHeight,
          playMod: app.globalData.playMod,
          play: app.globalData.play
        })


        if (app.globalData.closetimecurrent > 0) {
          this.setData({
            closetimecurrent: app.globalData.closetimecurrent,
            settimebool: true
          })
        }

        var that = this
        setTimeout(() => {
          that.setData({
            loadingbool: false
          })
        }, 1500)
        let flag = wx.getStorageSync('isOpenAD') || false
        if (!flag) {
          this.adverstise();
        }
        this.adverstise2()
        this.bannerList();
        this.categoryList()
        this.categoryListover()
        this.collectionList();

        var timestamp = Date.parse(new Date());
        this.setData({
          currentmonth: timestamp
        })
      }
    })
  },
  onReady() {
    this.Dialog = this.selectComponent('#Dialog');
  },
  onLoad() {
    this.config()


  },
  onUnload() {

  },
  onShow(){
    if(app.globalData.songlist && app.globalData.songlist.length>0){
      this.onTimeUpdate()
    }
  },
  getCurrentDay() {
    var date = new Date();
    var day = date.getDate();
    return day;
  },
  // 计算这个月有多少天
  getCurrentMonthDayNum: function () {
    let today = new Date();
    let dayAllThisMonth = 31;
    if (today.getMonth() + 1 != 12) {
      let currentMonthStartDate = new Date(today.getFullYear() + "/" + (today.getMonth() + 1) + "/01"); // 本月1号的日期
      let nextMonthStartDate = new Date(today.getFullYear() + "/" + (today.getMonth() + 2) + "/01"); // 下个月1号的日期
      dayAllThisMonth = (nextMonthStartDate - currentMonthStartDate) / (24 * 3600 * 1000);
    }
    return dayAllThisMonth;
  },
  // 点击签到按钮
  sign() {
    Controller.sign().then(res => {
      wx.showToast({
        title: res.msg,
        icon: 'success',
        duration: 2000
      })
      this.setData({
        issign: true
      })
      app.updateScore(4)
      this.signList()
    })
  },
  // 打开签到弹出窗
  opensign() {
    if (!wx.getStorageSync('logintoken')) {
      app.ToLogin();
    } else {
      this.signList()
      this.setData({
        signbool: true
      })
    }
  },
  signList() {
    let data = {
      month: formatTime3(this.data.currentmonth)
    }
    Controller.signList(data).then(res => {
      if (res.data.baseData.length > 0) {
        var list = res.data.baseData;
        var newlist = []
        var week = [{
            "week": "周日",
            "day": 0,
            "canSign": 0,
            "hasSign": 0
          },
          {
            "week": "周一",
            "day": 0,
            "canSign": 0,
            "hasSign": 0
          },
          {
            "week": "周二",
            "day": 0,
            "canSign": 0,
            "hasSign": 0
          },
          {
            "week": "周三",
            "day": 0,
            "canSign": 0,
            "hasSign": 0
          },
          {
            "week": "周四",
            "day": 0,
            "canSign": 0,
            "hasSign": 0
          },
          {
            "week": "周五",
            "day": 0,
            "canSign": 0,
            "hasSign": 0
          },
          {
            "week": "周六",
            "day": 0,
            "canSign": 0,
            "hasSign": 0
          }
        ]
        var contiue = true
        var weeknew = []
        // var yearmoth = ''
        // yearmoth = formatTime2(Date.parse(new Date(list[0].day)))

        for (var i = 0; i < list.length; i++) {
          list[i].day = Today(Date.parse(new Date(list[i].day)))
        }

        for (var i = 0; i < week.length; i++) {
          if (week[i].week == list[0].week) {
            contiue = false
          }
          if (contiue) {
            weeknew.push(week[i])
          }
        }
        list = weeknew.concat(list);
        var moth = Number(this.getCurrentMonthDayNum());
        if (list.length < moth) {
          var nums = list.length - weeknew.length;
          for (var i = 0; i < (moth - list.length); i++) {
            list.push({
              "week": "",
              "day": nums++,
              "canSign": 0,
              "hasSign": 0
            })
          }
        }
        var issign = false;
        var iscanSign = false;
        for (var i = 0; i < list.length; i++) {
          let today = new Date();
          let todayStartDate = Date.parse(new Date(today.getFullYear() + "/" + (today.getMonth() + 1) + "/01"));
          let currentday = new Date(this.data.currentmonth);
          let currentStartDate = Date.parse(new Date(currentday.getFullYear() + "/" + (currentday.getMonth() + 1) + "/01"));

          if (currentStartDate >= todayStartDate) {
            if (todayStartDate == currentStartDate) {
              var nowday = this.getCurrentDay()
              if (nowday < list[i].day) {
                list[i].canSign = 0
              }
              if (nowday == list[i].day) {
                if (list[i].canSign == 0) {
                  iscanSign = false
                } else {
                  iscanSign = true
                  if (list[i].hasSign != '-1') {
                    issign = true
                  } else {
                    issign = false
                  }
                }
              }
              this.setData({
                issign: issign,
                iscanSign: iscanSign
              })
            } else {
              list[i].canSign = 0
            }

          }

        }
        for (var i = 0; i < list.length; i += 7) {
          newlist.push(list.slice(i, i + 7));
        }
        this.setData({
          signListdata: newlist,
          signmoth: formatTime3(this.data.currentmonth, 2),
        })
      }
    })
  },
  prevmoths() {
    let date = new Date(this.data.currentmonth);
    let nowdate = new Date();
    let CurrentDate = "";
    let year = date.getFullYear();
    let yearnow = nowdate.getFullYear();
    let month = (date.getMonth()) < 10 ? "0" + (date.getMonth()) : (date.getMonth()); //自动补0
    let nowmonth = (nowdate.getMonth() + 1) < 10 ? "0" + (nowdate.getMonth() + 1) : (nowdate.getMonth() + 1);

    if (Number(yearnow) >= Number(year) - 1 && Number(year) <= Number(yearnow)) {
      if (Number(yearnow) - 1 == Number(year) && Number(month) < Number(nowmonth)) {
        return
      }
      if (Number(yearnow) == Number(year) && Number(month) > Number(nowmonth)) {
        return
      }
    } else {
      return
    }

    if (month < 1) {
      CurrentDate = (year - 1) + "-" + "12"
    } else {
      CurrentDate = year + "-" + month
    }

    var timestamp = Date.parse(CurrentDate);
    this.setData({
      currentmonth: timestamp
    })
    this.signList()
  },
  nextmoths() {
    let date = new Date(this.data.currentmonth);
    let nowdate = new Date();
    let CurrentDate = "";
    let year = date.getFullYear();
    let yearnow = nowdate.getFullYear();
    let month = (date.getMonth() + 1 + 1) < 10 ? "0" + (date.getMonth() + 1 + 1) : (date.getMonth() + 1 + 1);
    let nowmonth = (nowdate.getMonth() + 1) < 10 ? "0" + (nowdate.getMonth() + 1) : (nowdate.getMonth() + 1);
    if (Number(yearnow) >= Number(year) - 1 && Number(year) <= Number(yearnow)) {
      if (Number(yearnow) - 1 == Number(year) && Number(month) < Number(nowmonth)) {
        return
      }
      if (Number(yearnow) == Number(year) && Number(month) > Number(nowmonth)) {
        return
      }
    } else {
      return
    }
    if (month > 12) {
      CurrentDate = (year + 1) + "-" + "01"
    } else {
      CurrentDate = year + "-" + month
    }
    var timestamp = Date.parse(CurrentDate);
    this.setData({
      currentmonth: timestamp
    })
    this.signList()
  },
  closedate() {
    this.setData({
      signbool: false
    })
  },
  // 2是启动页广告，
  adverstise() {
    let data = {
      source: 2
    }
    // if(wx.getStorageSync("userInfo") && wx.getStorageSync("userInfo").id){
    //   data.id=wx.getStorageSync("userInfo").id
    // }
    Controller.bannerList(data).then(res => {
      this.setData({
        adverstisedata: res.data.baseData
      })
      wx.setStorageSync('isOpenAD', true)
      this.getCountDown()
    })
  },
  // 3首页中部广告
  adverstise2() {
    let data = {
      source: 3
    }
    // if(wx.getStorageSync("userInfo") && wx.getStorageSync("userInfo").id){
    //   data.id=wx.getStorageSync("userInfo").id
    // }
    Controller.bannerList(data).then(res => {
      console.log('adverstise2data', res.data.baseData)
      this.setData({
        adverstise2data: res.data.baseData
      })
    })
  },
  // 1是首页，
  bannerList() {
    var that = this;
    let data = {
      source: 1
    }
    if (wx.getStorageSync("userInfo") && wx.getStorageSync("userInfo").id) {
      data.id = wx.getStorageSync("userInfo").id
    }
    Controller.bannerList(data).then(res => {
      that.setData({
        banner: res.data.baseData
      })
      this.getheight();

    })
  },
  getCountDown() { //验证码一分钟倒计时
    var time = parseInt(this.data.adverstisetime);
    if (time <= 0) {
      this.setData({
        loadingbool: false,
        adverstisetime: 0
      })
      return false;
    }
    time--
    this.setData({
      adverstisetime: time
    })
    setTimeout(this.getCountDown, 1000);
  },
  onPageScroll: function (e) { // 获取滚动条当前位置
    let query = wx.createSelectorQuery()
    query.select('#singlists').boundingClientRect((rect) => {
      if(rect){
        let top = rect.top;
        if (top < this.data.navHeight) {
          this.setData({
            defaultFix: true,
            isFixedTop: true
          })
        } else {
          this.setData({
            isFixedTop: false,
            defaultFix: false
          })
        }
      }
    }).exec()
  },
  getheight() {
    let query = wx.createSelectorQuery()
    query.select('#defaulttop').boundingClientRect((rect) => {
      if (rect) {
        let height = rect.height;
        this.setData({
          defaulttopheight: height - this.data.navHeight
        })
      }
    }).exec()
  },

  tosearch() {
    wx.navigateTo({
      url: '/pages/Search/Search'
    })
  },
  swiper: function (e) {
    var index = e.detail.current
    this.setData({
      current: index
    })

  },


  categoryList() {
    Controller.categoryList({
      keyword: '',
      page: 1,
      pageSize: 10,
      isIndex: 1,
    }).then(res => {
      this.setData({
        meau: res.data.baseData.list
      })
      this.getheight();
    })
  },
  categoryListover() {
    Controller.categoryList({
      keyword: '',
      page: this.data.page,
      pageSize: this.data.pageSize,
      isIndex: "",
    }).then(res => {
      if (res.data.baseData.list.length > 0) {
        this.setData({
          singnav: this.data.singnav.concat(res.data.baseData.list)
        })
        if (res.data.baseData.lastPage) {
          this.setData({
            isEnd: true
          })
        }
        if (this.data.page == 1) {
          this.setData({
            singnavid: this.data.singnav[0].id
          })
          this.audioList()
        }
      }

    })
  },
  scrollend() {
    if (!this.data.isEnd) {
      this.setData({
        page: this.data.page + 1
      })
      this.categoryListover()
    }
  },
  singnav(e, singnavId) {
    var index = '',
      id = '';
    console.log('singnavId', singnavId, !Boolean(singnavId), typeof (singnavId) == 'undefined')
    if (typeof (singnavId) == 'undefined') {
      index = e.currentTarget.dataset.index;
      id = e.currentTarget.dataset.id;
    } else {
      index = e;
      id = singnavId
    }
    this.setData({
      singnavdata: [],
      singnavcurrent: index,
      singnavid: id,
      singnavpage: 1,
      singnavisEnd: false,
      singnisloading:true
    })
    this.audioList()
  },
  audioList() {
    Controller.audioList({
      sortBy: 3,
      categoryId: this.data.singnavid,
      page: this.data.singnavpage,
      pageSize: this.data.singnavpageSize
    }).then(res => {
      if (res.data.baseData.list.length > 0) {
        for (let item of res.data.baseData.list) {
          if (item.keywords) {
            item.keywords = item.keywords.split(',')
          }
        }
        this.setData({
          singnavdata: this.data.singnavdata.concat(res.data.baseData.list)
        })
        let singnavdataleft = [];
        let singnavdataright = [];

        if (this.data.singnavdata && this.data.singnavdata.length > 0) {
          for (let i = 0; i < this.data.singnavdata.length; i++) {
            if (i % 2 == 0) {
              singnavdataleft.push(this.data.singnavdata[i])
            } else {
              singnavdataright.push(this.data.singnavdata[i])
            }
          }
        }
        this.setData({
          singnavdataleft: singnavdataleft,
          singnavdataright: singnavdataright
        })
      }
      if (res.data.baseData.lastPage) {
        this.setData({
          singnavisEnd: true
        })
      }
      this.setData({
        singnisloading:false
      })
    })
  },
  onReachBottom() {
    let singnavcurrent = this.data.singnavcurrent;
    let length = this.data.singnav.length
    if (this.data.singnavisEnd) {
      if (singnavcurrent < length - 1) {
        singnavcurrent++
      } else {
        singnavcurrent = 0
      }
      let singnavItem = this.data.singnav.filter((item, index) => {
        if (singnavcurrent == index) {
          return item
        }
      })
      console.log(singnavItem)
      this.singnav(singnavcurrent, singnavItem[0].id)
      return;
    } else {
      this.setData({
        singnavpage: this.data.singnavpage + 1,
      });
      this.audioList()
    }
  },
  singnavnext() {
    var singnavcurrent = this.data.singnavcurrent;
    let length = this.data.singnav.length
    if (singnavcurrent < length - 1) {
      singnavcurrent++
    } else {
      singnavcurrent = 0
    }
    let singnavItem = this.data.singnav.filter((item, index) => {
      if (singnavcurrent == index) {
        return item
      }
    })
    this.setData({
      singnavcurrent: singnavcurrent
    })
    this.singnav(singnavcurrent, singnavItem[0].id)
    return
  },
  singnavprev() {
    var singnavcurrent = this.data.singnavcurrent;
    let length = this.data.singnav.length
    if (singnavcurrent > 0) {
      singnavcurrent--
    } else {
      singnavcurrent = length - 1
    }
    this.setData({
      singnavcurrent: singnavcurrent,
      singnavleftend: false
    })
    let singnavItem = this.data.singnav.filter((item, index) => {
      if (singnavcurrent == index) {
        return item
      }
    })
    this.singnav(singnavcurrent, singnavItem[0].id)
    return
  },
  // scroll(e) {
  //   this.setData({
  //     singnavleft: e.detail.scrollLeft,
  //     singnavleftend: false
  //   })
  // },

  albumnav(e) {
    var index = e.currentTarget.dataset.index;
    var text = e.currentTarget.dataset.text;
    this.setData({
      albumnavcurrent: index,
      sortBy: 2,
      ishot: true,
      albumlists1: [],
      albumlists2: []
    })
    if (index == 0) {
      this.setData({
        isMust: 0,
        isTopic: 1
      })
    }
    if (index == 2) {
      this.setData({
        isMust: 1,
        isTopic: 0
      })
    }
    if (index == 3) {
      return
    }
    this.collectionList();
  },
  hot() {
    this.setData({
      ishot: !this.data.ishot
    })
    if (this.data.ishot) {
      this.setData({
        sortBy: 2
      })
    } else {
      this.setData({
        sortBy: 1
      })
    }
    this.collectionList();
  },
  more() {
    wx.navigateTo({
      url: '/pages/Album/Album?isMust=' + this.data.isMust + '&isTopic=' + this.data.isTopic + '&sortBy=' + this.data.sortBy + '&albumnavcurrent=' + this.data.albumnavcurrent
    })
  },
  collectionList() {
    if (this.data.albumnavcurrent == 1) {
      // 热播
      Controller.audioList({
        sortBy: this.data.sortBy,
        isHotPlay: 1,
        page: 1,
        pageSize: 3
      }).then(res => {
        if (res.data.baseData.list.length > 0) {
          this.setData({
            albumlists2: res.data.baseData.list
          })
        }
      })
    } else if (this.data.albumnavcurrent == 0) {
      // 专题
      Controller.compilationList({
        sortBy: this.data.sortBy,
        isTopic: this.data.isTopic,
        page: 1,
        pageSize: 3
      }).then(res => {
        if (res.data.baseData.list.length > 0) {
          this.setData({
            albumlists1: res.data.baseData.list
          })
        }
      })
    } else {
      // 必听
      Controller.collectionList({
        sortBy: this.data.sortBy,
        isMust: this.data.isMust,
        page: 1,
        pageSize: 3
      }).then(res => {
        if (res.data.baseData.list.length > 0) {
          this.setData({
            albumlists1: res.data.baseData.list
          })
        }
      })
    }
  },
  mvlook(e) {
    wx.navigateTo({
      url: '/pages/weixinlink/weixinlink?url=' + e.currentTarget.dataset.url
    })
  },
  mvmin(e) {
    wx.navigateToMiniProgram({
      appId: e.currentTarget.dataset.id,
      path: e.currentTarget.dataset.path,
      extraData: {},
      envVersion: 'trial',
      success(res) {
        console.log(res)
        // 打开成功
      },
      fail(res){
        console.log(res)
      }
    })
  },
  playall(e) {
    var index = 0;
    if (e.currentTarget.dataset.index) {
      index = e.currentTarget.dataset.index
    }
    app.globalData.currentIndex = index
    app.globalData.songlist = this.data.albumlists2
    // this._init()

    wx.navigateTo({
      url: "/pages/Playing/Playing?categoryId=" + this.data.categoryId + "&sortBy=" + this.data.sortBy + "&currentIndex=" + index
    })
  },
  playsingle(e) {
    var index = 0;
    if (e.currentTarget.dataset.item) {
      app.globalData.currentIndex = 0
      app.globalData.songlist = [e.currentTarget.dataset.item]
      // this._init()
      wx.navigateTo({
        url: "/pages/Playing/Playing"
      })
    } else {
      wx.showToast({
        title: '本歌曲暂时不能播放。请切换下一首',
        icon: 'none'
      })
    }

  },
  albumgo(e) {
    var type = e.currentTarget.dataset.type;
    if (type == 1) {
      wx.navigateTo({
        url: '/pages/Exclusive/Exclusive?id=' + e.currentTarget.dataset.id
      })
    } else {
      wx.navigateTo({
        url: '/pages/Album/Detail/Detail?id=' + e.currentTarget.dataset.id + '&sortBy=' + this.data.sortBy
      })
    }

  },
  PopSlowSongs(e) {
    var categoryId = e.currentTarget.dataset.categoryid;
    var tag = e.currentTarget.dataset.tag;
    wx.navigateTo({
      url: "/pages/PopSlowSongs/PopSlowSongs?id=" + categoryId + "&title=" + tag
    })
  },

  //初始化
  _init(flag= false) {
    let currentIndex = app.globalData.currentIndex || 0;
    let songslist = (app.globalData.songlist.length && app.globalData.songlist)
    let currentSong = app.globalData.songlist[app.globalData.currentIndex] || (songslist && songslist[app.globalData.currentIndex])
    let duration = currentSong && currentSong.duration
    this.setData({
      currentSong: currentSong,
      duration: duration,
      songslist: songslist,
      currentIndex: currentIndex
    })
    if(flag){
      this._getPlayUrl(currentSong)
    }
    // this._getLyric(currentSong)
  },
  // 获取播放地址
  _getPlayUrl(currentSong) {
    const _this = this
    if (currentSong.audioUrl) {
      _this._createAudio(currentSong)
    } else {
      wx.showToast({
        title: '本歌曲暂时不能播放。请切换下一首',
        icon: 'none'
      })
    }
  },
  // 创建播放器
  _createAudio(currentSong) {

    if (manage.src != currentSong.audioUrl) {
      manage.src = currentSong.audioUrl
      manage.title = currentSong.title 
      manage.coverImgUrl=currentSong.imgUrl
      // wx.playBackgroundAudio({
      //   dataUrl: currentSong.audioUrl,
      //   title: currentSong.title,
      //   coverImgUrl: currentSong.imgUrl
      // })
      app.updateScore(5,currentSong.id)
    }
    this.listenmusic(currentSong)
  },
  listenmusic(currentSong){
    // 监听音乐播放。
    manage.onPlay(()=>{
      this.setData({
        play: 2,
      })
      app.globalData.play = 2
      app.globalData.currentSong = this.data.currentSong
      app.play(this.data.currentSong.id)
    })
    // 监听音乐暂停。
    manage.onPause(()=>{
      this.setData({
        play: 1,
      })
      app.globalData.play = 1
      app.globalData.currentSong = this.data.currentSong
      // 更新收听时长接口
      Controller.uploadListenTimes({
          seconds: parseInt(this.data.currentTime)
        })
        .then(res => {

        })
    })
    
    manage.onEnded(()=>{
      this.setData({
        play: 1,
      })
      app.globalData.play = 1
      app.globalData.currentSong = this.data.currentSong
      Controller.uploadListenTimes({
          seconds: parseInt(this.data.currentTime)
        })
        .then(res => {

        })
      if (this.data.playMod === SINGLE_CYCLE_MOD) {
        this._init(true)
        return
      }

      this.endnext()
    })
    this.onTimeUpdate()
  },
  endnext() {
    if (app.globalData.currentIndex != this.getNextIndex(true)) {
      app.globalData.currentIndex = this.getNextIndex(true)
      this._init(true)
    }
  },
  onTimeUpdate(time) {
    // 监听播放拿取播放进度
    if (time) {
      manage.seek(time);
    }
    manage.onTimeUpdate(() => {
      const currentTime = manage.currentTime;
      const duration = manage.duration
      this.setData({
        currentTime: this._formatTime(currentTime),
        duration: this._formatTime(duration),
        percent: currentTime / duration * 100,
        sildercurrent:(this.data.percent*394)/100
      })
    })
  },
  // 滑动
  musicchange(e) {
    var current = Number(e.detail.value);
    var duration = this._formatSecod(this.data.duration) || 0;
    var max = 394
    var change = '';
    change = current / max * duration;
    manage.seek((change || 0))
    this.onTimeUpdate(change)
  },
  _formatSecod(time) {
    time = time || 0
    if (time) {
      var min = time.split(':')[0];
      var sec = time.split(':')[1];
      var s = Number(min * 60) + Number(sec);
    } else {
      s = 0
    }
    return s
  },

  _formatTime(interval) {
    interval = interval | 0
    const minute = interval / 60 | 0
    const second = this._pad(interval % 60)
    return `${minute}:${second}`
  },
  /*秒前边加0*/
  _pad(num, n = 2) {
    let len = num.toString().length
    while (len < n) {
      num = '0' + num
      len++
    }
    return num
  },
  prev() {
    app.globalData.currentIndex = this.getNextIndex(false)
    this._init(true)
  },
  next() {
    app.globalData.currentIndex = this.getNextIndex(true)
    this._init(true)
  },
  changeMod() {
    let playMod = this.data.playMod + 1
    if (playMod > SINGLE_CYCLE_MOD) {
      playMod = SEQUENCE_MODE
    }
    this.setData({
      playMod: playMod
    })
    app.globalData.playMod = playMod
  },
  getNextIndex(nextFlag) {
    let ret,
      currentIndex = app.globalData.currentIndex,
      mod = this.data.playMod,
      len = this.data.songslist.length
    if (mod === RANDOM_MOD) {
      ret = randomNum(len)
    } else {
      if (nextFlag) {
        ret = currentIndex + 1 == len ? 0 : currentIndex + 1
      } else {
        ret = currentIndex - 1 < 0 ? len - 1 : currentIndex - 1
      }
    }
    return ret
  },
  togglePlaying(e) {
    var that = this;
    if(app.globalData.play==1){
      if (manage.src== that.data.banner[that.data.current].audioList) {
        wx.getBackgroundAudioPlayerState({
          success(res) {
            var play = 1;
            var status = res.status
            if (status == 1) {
              manage.pause()
              play = 1
            } else {
              manage.play()
              play = 2
            }
            that.setData({
              play: play,
              playcurrent: that.data.current
            })
          }
        })
      } else {
        app.globalData.songlist = that.data.banner[that.data.current].audioList
        that._init(true);
      }
    }else{
      wx.getBackgroundAudioPlayerState({
        success(res) {
          var play = 1;
          var status = res.status
          if (status == 1) {
            manage.pause()
            play = 1
          } else {
            manage.play()
            play = 2
          }
          that.setData({
            play: play,
            playcurrent: that.data.current
          })
        }
      })
    }
    that.selectComponent('#Footer').playmusic();
  },

  bindPickerChange: function (e) {
    var that = this;
    that.Dialog.ShowDialog({
      type: 'Pager',
      callback: res => {
        this.Dialog.CloseDialog();
      }
    })
  },
  toastTime(res) {
    var time = res.detail.time;
    var close = res.detail.close;
    if (time > 0 && !close) {
      this.setData({
        closetimecurrent: time,
        settimebool: true,
      })
    } else {
      if (close) {
        this.setData({
          closetimecurrent: 0,
          settimebool: false
        })
      } else {
        this.setData({
          closetimecurrent: 0,
          settimebool: false,
          play: 1
        })
        manage.pause()
      }
    }
  },
  onShareAppMessage: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },
  onShareTimeline: function (e) {
    // if (e.from == "button") {
      let obj = {
        title: '有氧FM',
        success: function (res) {
          
        },
        fail(err) {
          
        }
      }
      return obj
    // }
  },

})